define(['app'], function(app) {
    app.controller('CategoryEditController', ['Dialog', 'Context', 'CategoryService',
        function(Dialog, Context, CategoryService) {
        var self = this;
        self.categoryParentId = null;
        self.categoryParentIdRequired = false;
        self.categoryParentIdDisabled = true;

        self.init = function() {
            if (Context.data) {
                self.categoryId = Context.data.id;
                self.categoryName = Context.data.name;
                if (Context.data.parentId) {
                    self.categoryParentId = Context.data.parentId;
                }
            }
            if (self.categoryParentId != null && self.categoryId != self.categoryParentId) {
                self.categoryParentIdRequired = true;
            }
            if (self.categoryParentIdRequired || self.categoryParentId == null) {
                self.categoryParentIdDisabled = false;
            }
            CategoryService.getParentCategory({}).then(function(resp) {
                self.category = resp.data;
            });
        };

        self.save = function(valid) {
            if (valid) {
                if (self.categoryParentIdRequired && self.categoryParentId == null) {
                    return;
                }
                CategoryService.saveCategory({
                    id: self.categoryId,
                    name: self.categoryName,
                    parentId: self.categoryParentId
                }).then(function(resp) {
                    if (resp.success) {
                        Context.success = true;
                        Context.close();
                    }
                });
            }
        };
    }]);
});
